package ua.org.nuos.sdms.middle.service;

import org.apache.commons.lang.Validate;
import ua.org.nuos.configuration.SdmsConfiguration;
import ua.org.nuos.sdms.crypt.Cipher;
import ua.org.nuos.sdms.crypt.CipherFactory;
import ua.org.nuos.sdms.middle.dao.UserDaoBean;
import ua.org.nuos.sdms.middle.entity.User;
import ua.org.nuos.sdms.middle.entity.enums.EmailStatus;
import ua.org.nuos.sdms.middle.util.CodeUtil;
import ua.org.nuos.sdms.middle.util.MailMessageConstructor;
import ua.org.nuos.sdms.middle.util.exception.DuplicateEmailException;
import ua.org.nuos.sdms.middle.vo.CustomMessage;

import javax.annotation.PostConstruct;
import javax.annotation.security.PermitAll;
import javax.ejb.EJB;
import javax.ejb.Stateless;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 06.11.11
 * Time: 13:12
 * To change this template use File | Settings | File Templates.
 */
@Stateless
public class RegistrationServiceBean implements RegistrationServiceLocal {

    @EJB(beanName = "UserDaoBean")
    protected UserDaoBean userDaoBean;

    @EJB(beanName = "EmailVerificationServiceBean")
    protected EmailVerificationServiceLocal emailVerificationService;

    private Cipher cipher;

    @PostConstruct
    public void before() {
        cipher = CipherFactory.getCipher();
    }

    /**
     * Register new user in the system
     *
     * @param user user with password
     * @throws DuplicateEmailException
     */
    @PermitAll
    @Override
    public void registerNewUser(User user) throws DuplicateEmailException {
        Validate.notNull(user);

        User nullUser = userDaoBean.findByEmail(user.getEmail());
        if (nullUser != null) {
            throw new DuplicateEmailException(user.getEmail());
        }

        //hash password
        user.setPassword(cipher.cipher(user.getPassword()));

        user.setEmailStatus(EmailStatus.UNKNOWN);

        //create new user
        userDaoBean.createUser(user);

        //send email verification mail to complete registration
        emailVerificationService.sendEmailVerificationMessage();
    }
}
